//
//  SettingViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/29.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class SettingViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "设置"
    }

    @IBOutlet private weak var tableview: UITableView! {
        didSet {
            tableview.backgroundColor = .background
            tableview.tableFooterView = UIView()
            tableview.register(SettingViewCell.nibForCell(),
                               forCellReuseIdentifier: SettingViewCell.reuseIdentifier())
            tableview.register(SettingLogoutCell.nibForCell(),
            forCellReuseIdentifier: SettingLogoutCell.reuseIdentifier())
        }
    }

}

// MARK: - DataSource && Delegate
extension SettingViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SettingViewCell.reuseIdentifier(),
                                                     for: indexPath) as! SettingViewCell
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: SettingLogoutCell.reuseIdentifier(),
                                                                for: indexPath) as! SettingLogoutCell
            cell.logoutBtn.addTarget(self, action: #selector(logout), for: .touchUpInside)
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 44
        }
        return 150
    }
}

extension SettingViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.row == 0 {
            pushChangePsdVc()
        }
    }
    
    @objc private func logout() {
        WebSocketManager.destroy()
        UserDefaults.removeUserInfo()
        (mainWindow.rootViewController as? MainViewController)?.selectedIndex = 0
        dismiss(animated: true, completion: nil)
    }
    
    private func pushChangePsdVc() {
        let changePsdVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "changePwdVcId") as! ChangePwdViewController
        navigationController?.pushViewController(changePsdVc, animated: true)
    }
}
